package com.etl.dataflow.scheduler.admin.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.etl.dataflow.scheduler.admin.entity.request.PageRequest;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Consumer;

public interface DefaultService<T> {

    Set<String> SEARCH_EXCLUDE_FIELDS = new HashSet<>(Arrays.asList("id", "idt", "udt", "creatorName"));

    default Page<T> toPage(PageRequest pageRequest) {
        return new Page<>(pageRequest.getCurrentPage(), pageRequest.getPageSize());
    }

    default QueryWrapper<T> orLikeAllFields(PageRequest pageRequest, Class<? extends T> tClass, String orderField) {
        QueryWrapper<T> queryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(pageRequest.getKeyword())) {
            Field[] declaredFields = tClass.getDeclaredFields();
            TableField annotation;
            for (Field field : declaredFields) {
                annotation = field.getAnnotation(TableField.class);
                if (annotation == null || SEARCH_EXCLUDE_FIELDS.contains(field.getName())) {
                    continue;
                }
                queryWrapper.like(annotation.value(), pageRequest.getKeyword()).or();
            }
        }
        queryWrapper.orderByDesc(orderField);
        return queryWrapper;
    }

    default QueryWrapper<T> orLikeAllFieldsWithCustomCondition(PageRequest pageRequest,
                                                               Class<? extends T> tClass,
                                                               String orderField,
                                                               Consumer<QueryWrapper<T>> queryWrapperConsumer) {
        QueryWrapper<T> queryWrapper = orLikeAllFields(pageRequest, tClass, orderField);
        queryWrapperConsumer.accept(queryWrapper);
        return queryWrapper;
    }
}
